<script setup>
import { userlist, DelUser, searchUser } from '@/utils/lxz-axios'
import { ref, onMounted } from 'vue'
import setUser from '@/components/userManage/setUser.vue'

const uslist = ref(null)
let p = ref(1)

userlist(p.value).then((res) => {
  count.value = res.data.count
  uslist.value = res.data.userlist
})

// 添加pet
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'

const drawer = ref(false)
const drawer2 = ref(false)

const direction = ref('rtl')

// 刷新
const Resuserlist = () => {
  userlist(p.value).then((res) => {
    count.value = res.data.count
    uslist.value = res.data.userlist
    // console.log("更新",uslist.value);
    ElMessage.success('刷新成功')
  })
}

// 用户ID显示隐藏
const showId = ref(false)
const classshow = ref('white')
const ShowIdClick = () => {
  showId.value = !showId.value
  if (showId.value) {
    classshow.value = 'blue'
  } else {
    classshow.value = 'white'
  }
}

// 确认修改后的结果
const handleDrawer = () => {
  if (delbtn.value) {
    searchEnter(p.value)
    drawer.value = false
    drawer2.value = false
  } else {
    drawer.value = false
    drawer2.value = false

    console.log('更新1111')

    userlist(p.value).then((res) => {
      count.value = res.data.count
      uslist.value = res.data.userlist
      // console.log("更新",uslist.value);
    })
  }
}

// 中断提示
const handleClose2 = (done) => {
  ElMessageBox.confirm('修改状态不会保存，是否退出?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

let filterPet = null
const updatePet = (id) => {
  drawer2.value = true
  //   let updateUesr = uslist.value.find((item) => item._id == id)
  filterPet = uslist.value.find((item) => item._id == id)
  // console.log(filterPet.value);
}

// 删除
const deletePet = async (id) => {
  ElMessageBox.confirm(`确定要删除用户(id:${id})吗？`)
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '敏感操作，正在验证！',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let tok = localStorage.getItem('token')

      //   console.log(id, tok)

      DelUser(id, tok).then((res) => {
        console.log(res.data)

        if (res.data.delcode == 1) {
          ElMessage.success(res.data.msg)
          loading.close()

          if (delbtn.value) {
            searchEnter(p.value)
          } else {
            userlist(p.value).then((res) => {
              count.value = res.data.count
              uslist.value = res.data.userlist
              // console.log("更新",uslist.value);
            })
          }
        } else {
          ElMessage.error(res.data.msg)
          loading.close()
          // done()
        }
      })
      //   setTimeout(() => {
      //     loading.close()
      //     done()
      //   }, 2000)
    })
    .catch(() => {
      // catch error
    })
}

// 查询
let search = ref('')
let searchinp = ref('')
let delbtn = ref(false)

// 切换字段事件
const changeSec = () => {
  console.log(search.value)
  switch (search.value) {
    case '1':
      break
    case '2':
      break
    case '3':
      restaurants.value = [{ value: '管理员' }, { value: '用户' }, { value: '认证用户' }]
      break
    case '4':
      restaurants.value = [{ value: '正常' }, { value: '封禁' }, { value: '异常' }]
      break
    default:
      break
  }
}

// 提交搜索结果
const searchEnter = (num) => {
  p.value = num
  if (search.value && searchinp.value) {
    let inp = ''
    if (search.value == '3') {
      searchinp.value == '管理员'
        ? (inp = 'admin')
        : searchinp.value == '认证用户'
        ? (inp = 'vip')
        : searchinp.value == '用户'
        ? (inp = 'user')
        : (inp = searchinp.value)
    } else if (search.value == '4') {
      searchinp.value == '正常'
        ? (inp = 'Active')
        : searchinp.value == '封禁'
        ? (inp = 'Locked')
        : searchinp.value == '异常'
        ? (inp = 'Suspended')
        : (inp = searchinp.value)
    } else {
      inp = searchinp.value
    }

    console.log('code:', search.value, 'input', inp)

    delbtn.value = true

    searchUser(search.value, inp, num).then((res) => {
      console.log('搜索结果', res.data)
      if (res.data.Seacode == 1) {
        count.value = res.data.count
        uslist.value = res.data.userlist

        // if (p.value > res.data.count) {
        //   p.value = 1
        // }
      } else {
        ElMessage.error(res.data.error)
      }
    })
  } else {
    ElMessage.error('请选择搜索类型和输入搜索内容')
  }
}

// 退出搜索模式
const searchOut = () => {
  delbtn.value = false
  search.value = ''
  searchinp.value = ''
  restaurants.value = []
  p.value = 1
  userlist(p.value).then((res) => {
    count.value = res.data.count
    uslist.value = res.data.userlist
  })
}

// 分页器事件

const count = ref(0)
const switchPage = (val) => {
  if (delbtn.value) {
    p.value = val

    searchEnter(p.value)
    drawer.value = false
    drawer2.value = false
  } else {
    p.value = val
    userlist(p.value).then((res) => {
      count.value = res.data.count
      uslist.value = res.data.userlist
    })
  }
}

// 搜索提示代码
const state1 = ref('')

const restaurants = ref([])
const querySearch = (queryString, cb) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value

  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}
const loadAll = () => {
  return [
    // { value: '暂无建议' },
  ]
}

const handleSelect = (item) => {
  console.log(item)
}

onMounted(() => {
  restaurants.value = loadAll()
})
</script>

<template>
  <div>
    <header>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }"> homepage </el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
      <div style="display: flex; align-items: center; justify-content: space-between">
        <div
          v-show="delbtn"
          class="icon"
          @click="searchOut"
          style="flex-shrink: 0; background-color: #f56c6c; margin-right: 10rem"
        >
          退出查询模式
        </div>
        <!-- 选择器 -->
        <div style="height: 25rem; display: flex; align-items: center">
          <el-select
            v-model="search"
            class="m-2"
            placeholder="请选择字段"
            style="width: 100rem"
            @change="changeSec"
          >
            <el-option
              v-for="item in [
                { value: '1', label: '用户ID' },
                { value: '2', label: '用户名' },
                { value: '3', label: '用户类型' },
                { value: '4', label: '账户状态' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-autocomplete
          v-model="searchinp"
          :fetch-suggestions="querySearch"
          clearable
          class="inline-input w-50"
          placeholder="请输入搜索内容"
          @select="handleSelect"
          style="width: 180rem; margin-left: 10rem; display: flex; align-items: center"
        />
        <div class="icon" @click="searchEnter(1)" style="flex-shrink: 0">查询</div>
      </div>
    </header>
    <!-- <div style="margin: 8rem 0 0 0">&nbsp;</div> -->
    <div class="main">
      <div class="table-container">
        <table border="1">
          <thead>
            <tr>
              <th v-show="showId">用户ID</th>
              <th>用户名</th>
              <th style="text-align: center">用户类型</th>
              <th>注册日期</th>
              <th style="text-align: center">账户状态</th>

              <th style="text-align: center">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in uslist" :key="user._id" class="td-tag">
              <td v-show="showId">{{ user._id }}</td>
              <td>{{ user?.username }}</td>
              <td>
                <div class="tag1">
                  <el-tag v-if="user?.usertype == 'admin'" class="ml-2" type="warning"
                    >管理员</el-tag
                  >
                  <el-tag v-if="user?.usertype == 'user'" class="ml-2" type="success">用户</el-tag>
                  <el-tag v-if="user?.usertype == 'vip'" class="ml-2">认证用户</el-tag>

                  <el-tag v-if="user?.ssid" class="ml-2" type="success" style="margin-left: 10rem"
                    >微信用户</el-tag
                  >
                </div>
              </td>
              <td>{{ user?.time }}</td>
              <td>
                <!-- {{ user?.userstate }} -->
                <div class="tag1">
                  <el-tag
                    size="large"
                    v-if="user?.userstate == 'Active'"
                    class="ml-2"
                    type="success"
                    >正&nbsp;&nbsp;&nbsp;常</el-tag
                  >
                  <el-tag
                    size="large"
                    v-if="user?.userstate == 'Suspended'"
                    class="ml-2"
                    type="warning"
                    >异&nbsp;&nbsp;&nbsp;常</el-tag
                  >
                  <el-tag
                    size="large"
                    v-if="user?.userstate == 'Locked'"
                    class="ml-2"
                    type="danger "
                    >封&nbsp;&nbsp;&nbsp;禁</el-tag
                  >
                </div>
              </td>

              <td class="btntd">
                <div class="btn">
                  <button
                    class="one iconfont icon-xiugai"
                    @click.stop="updatePet(user._id)"
                    title="修改用户信息"
                  ></button>
                  <button
                    title="删除用户"
                    class="del iconfont icon-shanchu"
                    @click.stop="deletePet(user._id)"
                  ></button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加 -->
    <!-- <el-drawer
      v-model="drawer"
      title="添加新的用户"
      :direction="direction"
      size="50%"
      :before-close="handleClose"
    >
      <Adduslist @handleDraewr="handleDrawer"></Adduslist>
    </el-drawer> -->

    <!-- 修改 -->
    <el-drawer
      v-model="drawer2"
      title="修改用户信息"
      :direction="direction"
      size="50%"
      :before-close="handleClose2"
    >
      <setUser @handleDraewr="handleDrawer" :filterPet="filterPet" :key="filterPet"></setUser>
    </el-drawer>

    <div class="pagination">
      <div class="endBtn">
        <div class="icon" @click="Resuserlist" title="刷新列表">
          <el-icon color="#FFFFFF" class="iconRS"><Refresh /></el-icon>
        </div>
        <div class="icon" :class="classshow" @click="ShowIdClick" title="展示/隐藏用户ID">
          <el-icon color="#FFFFFF" v-show="showId"><UserFilled /></el-icon>
          <el-icon color="#555555" v-show="!showId"><User /></el-icon>
        </div>
      </div>
      <el-pagination
        v-model:current-page="p"
        background
        layout="prev, pager, next"
        :total="count * 10"
        @current-change="switchPage"
      />
    </div>
  </div>
</template>



<style lang="less" scoped>
@import url(../../css/icon.css);

.td-tag {
  .tag1 {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.pagination {
  width: 96%;
  display: flex;
  padding: 0 20rem;
  justify-content: space-between;
  align-items: center;
  .endBtn {
    display: flex;
    .icon {
      width: 25rem;
      height: 25rem;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f0f0f0;
      margin-right: 10rem;
      border-radius: 4rem;
      background-color: #409eff;
      cursor: pointer;
      .iconRS {
        transition: all 1s;
        &:hover {
          transform: rotate(-180deg);
        }
      }
    }
  }
}

header {
  padding: 10rem 30rem 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .icon {
    padding: 5rem 10rem;
    background-color: #409eff;
    color: #fff;
    border-radius: 4rem;
    margin-left: 8rem;
    font-size: 12rem;
    cursor: pointer;
  }
}

.select {
  height: 0;
  visibility: hidden;
  opacity: 0;
  margin: 8rem 20rem;
  padding: 0 20rem;
  background-color: #fff;
  border-radius: 10rem;
  transition: all 1s;
}

.main {
  z-index: 99;
  @theme-color: #f8f9fa;

  .table-container {
    margin: 20rem;
    font-family: 'Arial', sans-serif;
  }

  h2 {
    color: @theme-color;
    font-size: 24rem;
    margin-bottom: 18rem;
    display: flex;
    justify-content: space-between;

    .add {
      font-size: 20rem;

      button {
        padding: 6rem 12rem;
        border: none;
        cursor: pointer;
        border-radius: 4rem;
        font-size: 18rem;
        transition: background-color 0.3s;
        background-color: #409eff;
        color: white;
      }
    }
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10rem;
    background-color: #fff;
    box-shadow: 0 4rem 10rem rgba(0, 0, 0, 0.05);
    border-radius: 8rem;
    overflow: hidden;
  }

  th,
  td {
    padding: 6rem 15rem;
    font-size: 14rem;
    text-align: left;
    border: 1rem solid #e0e0e0;
  }

  .btntd {
    padding: 6rem 0;
  }

  th {
    background-color: @theme-color;
    color: #9c9c9c;
    font-weight: 600;
    font-size: 14rem;
  }

  tbody tr:nth-child(even) {
    background-color: #f7f7f7;
  }

  tbody tr:hover {
    background-color: #f1f1f1;
  }

  tbody {
    .btn {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-evenly;

      .del {
        background-color: #ff4d4f;
        color: white;
      }

      .one {
        // background-color: #16ceaf;
        color: rgb(0, 0, 0);
      }
    }
  }

  .edit-btn {
    background-color: @theme-color;
    color: #fff;
    margin-right: 8rem;

    &:hover {
      background-color: darken(@theme-color, 10%);
    }
  }

  .delete-btn {
    background-color: #ff4d4f;
    color: #fff;

    &:hover {
      background-color: darken(#ff4d4f, 10%);
    }
  }
}

// .pagination {
//   width: 96%;
//   display: flex;
//   padding: 0 20rem;
//   justify-content: end;
// }

.el-form--inline .el-form-item {
  width: 100%;
}

.el-button,
.el-button.is-round {
  margin: auto;
  padding: 0 26rem;
}

.el-form {
  padding-top: 15rem;
}

// 按钮样式
.white {
  background-color: #f0f0f0 !important;
  transition: all 0.5s;
}

.blue {
  background-color: #409eff !important;
  transition: all 0.5s;
}
</style>